package com.supermarket.interceptor;

import com.alibaba.fastjson.JSON;
import com.supermarket.context.UserContext;
import com.supermarket.entity.User;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.concurrent.TimeUnit;

@Slf4j
@Component
@RequiredArgsConstructor
public class LoginTokenInterceptor implements HandlerInterceptor {

    private final StringRedisTemplate redisTemplate;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        log.info("请求被拦截: {}", request.getRequestURL().toString());

        // 跨域预检请求（OPTIONS方法）直接放行
        if ("OPTIONS".equals(request.getMethod())) {
            return true;
        }

        // 从请求头获取token
        String token = request.getHeader("token");
        if (!StringUtils.hasLength(token)) {
            log.error("请求中缺少token");
            response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
            response.getWriter().write("Token 是必需的");
            return false;
        }

        // 从 Redis 验证 token
        String strUser = redisTemplate.opsForValue().get("user:login:" + token);
        if (!StringUtils.hasLength(strUser)) {
            log.error("无效或过期的 token: {}", token);
            responseNoLoginInfo(response);
            return false;
        }

        // 解析用户信息并存入 ThreadLocal
        User user = JSON.parseObject(strUser, User.class);
        UserContext.setCurrentId(user.getId());


        // 延长 Redis 中 token 的过期时间
        redisTemplate.expire("user:login:" + token, 30, TimeUnit.MINUTES);

        log.info("Token 验证成功，用户 ID: {}", user.getId());
        return true;
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
        HandlerInterceptor.super.postHandle(request, response, handler,modelAndView);
    }

    private void responseNoLoginInfo(HttpServletResponse response) throws Exception {
        response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
        response.getWriter().write("用户未登录或 token 过期");
    }
}
